<?php

//Here is where I register the Metabox

add_action( 'add_meta_boxes', 'species_add_metabox', 10, 2 );
add_action( 'save_post', 'animal_rescue_port_on_post_save', 10, 2);

function species_add_metabox( $post_type, $post ){
			 add_meta_box('species-meta', 	//CSS id of the <DIV> that wraps our metabox
			'Animal Details',				//title of the metabox
			'species_display_metabox',    	//callback for rendering metabox content
			'animal',						//Post type for meta box display-page, post, etc 				
			'normal',						//Context - part of the page where the meta willshow
			'high'							//priority of meta box display	
			);
	
	}
	

//Here is where I create the Metabox
function species_display_metabox( $post ) {
	

	//retrieves as an array if it finds data - 
	$species_input = get_post_meta( $post->ID, 'species_meta', true );
	
	//default values if no data found. 
	if( $species_input == false){
		$species_input = array();
		$species_input['species'] = '';
		$species_input['breed'] = '';
		$species_input['gender'] = '';	
		$species_input['size'] = '';	
		$species_input['age'] = '';
		$species_input['spay_neut'] = '';
		$species_input['blog'] = '';
		$species_input['foster_location'] = '';
		$species_input['adopted'] = '';
	}
		//converts $portfolio_input array into variables. 
	extract( $species_input );
	
	
	//display the form
	include 'input_metabox.php';
	
}

//this function will run when a post is saved.  	
function animal_rescue_port_on_post_save( $post_id, $post ){
	
	//this is to prevent data from autosaving. Looking in the database at the post_type table
	if( $post->post_type=='revision'){
		return;
	
	}
	
	if( isset( $_POST['animal'])){
		
		$species_input=$_POST['animal'];
		
		//stripping the tags and storing it to itself - sanitizing
		$species_input['breed'] = strip_tags( $species_input['breed']);
		$species_input['age'] = absint( $species_input['age']);
		$species_input['url'] = esc_url( $species_input['url']);
		$species_input['blog'] = esc_url( $species_input['blog']);
		$species_input['foster_location'] = strip_tags( $species_input['foster_location']);
		$species_input['adopted'] = strip_tags( $species_input['adopted']);
		
		//var_dump( $species_input );
		//this stops the code from executing. 
		//throw new Exception('animal save');
		//first argument is the id of the post we want to attach it to, second is metakey
		update_post_meta ( $post_id, 'species_meta', $species_input );
		
	
		}
	
}


?>
